package cn.wolfcode.trip.core.service.impl;

import cn.wolfcode.trip.core.domain.Travel;
import cn.wolfcode.trip.core.domain.TravelContent;
import cn.wolfcode.trip.core.mapper.TravelContentMapper;
import cn.wolfcode.trip.core.mapper.TravelMapper;
import cn.wolfcode.trip.core.query.TravelQueryObject;
import cn.wolfcode.trip.core.service.ITravelService;
import cn.wolfcode.trip.core.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;

    @Autowired
    private TravelContentMapper contentMapper;

    public PageInfo query(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public void saveOrUpdate(Travel travel) {
        if(travel.getId() == null){
            //设置作者
            travel.setAuthor(UserContext.getCurrentUser());
            travelMapper.insert(travel);
            //处理内容表
            TravelContent travelContent = travel.getTravelContent();
            travelContent.setId(travel.getId());//主键关联
            contentMapper.insert(travelContent);
        }else {
            //设置最后更新时间
            travel.setLastUpdateTime(new Date());
            travelMapper.updateByPrimaryKey(travel);
            //处理内容表
            TravelContent travelContent = travel.getTravelContent();
            travelContent.setId(travel.getId());//主键关联
            contentMapper.updateByPrimaryKey(travelContent);
        }
    }

    public Travel getById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    public TravelContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    public void updateState(Travel travel) {
        //判断是否是发布状态
        if(travel.getState()==Travel.STATE_RELEASE){
            travel.setReleaseTime(new Date());
        }
        travelMapper.updateState(travel);
    }
}
